<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

</body>
<script>
// pid是parentId的简写,父id
let list = [
  {id: 1, name: '节点1', pid: ''},
  {id:11, name: '节点1-1', pid: 1},
  {id:111, name: '节点1-1-1', pid: 11},
  {id:12, name: '节点1-2', pid: 1},
  {id: 2, name: '节点2', pid: ''}
]
//方式一 不使用递归
// list.forEach(t=> {
//   let children = list.filter(m => t.id === m.pid)
//   if (children.length>0) {
//     t.children = children
//   }
// })
// let res = list.filter(t=>  t.pid ==='')
// console.log(res);
//方式二 不完整写法 少穿参数 递归
// function t(pid) {
//   let arr = []
//   list.forEach(t => {
//     if (t.pid === pid) {
//       let children = (t.id)
//       if(children.length>0) {
//         t.children = children
//       }
//       arr.push(t)
//     }
//   })
//   return arr
// }
// let res = t('')
// console.log(res);
//方式三 完整写法 多传参数 避免使用全局数据
function p(l,pid) {
  let arr = []
  l.forEach(t => {
    if (t.pid === pid) {
      let children = p(l,t.id)
      if(children.length>0) {
        t.children = children
      }
      arr.push(t)
    }
  })
  return arr
}
let res = p(list,'')
console.log(res);
let str = 'str'
console.log(str==='str');
</script>
</html>
